package zl.controller;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import zl.bean.Admin;
import zl.bean.RespBean;
import zl.service.AdminService;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/api/admin")
@Validated
public class AdminController {
    @Autowired
    private AdminService adminService;

    @GetMapping("/page")
    @ResponseBody
    public RespBean selectAllAdmin(){
        List<Admin> list = new ArrayList<>();
        list=adminService.selectAllAdmin();
        return RespBean.ok("查询成功",list);
    }

    @PostMapping("/add")
    @ResponseBody
    public RespBean addAdmin(@RequestBody @Validated Admin admin){
        if(StrUtil.hasBlank(admin.getUsername())|| StrUtil.hasBlank(admin.getPassword())){
            return RespBean.error("账号，密码不能为空");
        }
        int i = adminService.addAdmin(admin);
        if(i==1){
            return RespBean.ok("添加成功");
        }else if(i==3){
            return RespBean.error("账号重复，请重新填写");
        }else {
            return RespBean.error("添加失败");
        }

    }

    @GetMapping("/{id}")
    @ResponseBody
    public RespBean selectById(@PathVariable @NotNull(message = "管理员id不能为空") Integer id){
        Admin admin = adminService.selectById(id);
        return RespBean.ok("查询成功",admin);
    }


    @PostMapping("/update")
    @ResponseBody
    public RespBean updateAdmin(@RequestBody @Validated Admin admin){
        if(StrUtil.hasBlank(admin.getUsername()) || StrUtil.hasBlank(admin.getPassword())){
            return RespBean.error("用户名,密码不能为空");
        }
        int i = adminService.updateAdmin(admin);
        if(i==1){
            return RespBean.ok("修改成功");
        }else{
            return RespBean.error("修改失败");
        }
    }

    @DeleteMapping("/{id}")
    @ResponseBody
    public RespBean deleteAdmin(@PathVariable @NotNull(message = "管理员id不能为空") Integer id){
        int i =adminService.deleteAdmin(id);
        if(i==1){
            return RespBean.ok("删除成功");
        }else{
            return RespBean.error("删除失败");
        }
    }


}
